package com.example.uploadminio.service;

import com.example.uploadminio.model.MinioProperties;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

public class ConfigManager {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final String APP_DIR = System.getenv("APPDATA") != null
            ? System.getenv("APPDATA") + File.separator + "UploadMinioTool"
            : System.getProperty("user.home") + File.separator + ".uploadminio";
    private static final String CONFIG_PATH = APP_DIR + File.separator + "config.json";

    public static MinioProperties load() {
        try {
            File f = new File(CONFIG_PATH);
            if (f.exists()) {
                return MAPPER.readValue(f, MinioProperties.class);
            }
        } catch (Exception ignored) {}
        // 默认配置
        MinioProperties cfg = new MinioProperties();
        cfg.setEndpoint("http://127.0.0.1:9000");
        cfg.setBucket("bucket");
        cfg.setBucketPrefix("demo/demo");
        cfg.setAccessKey("minioadmin");
        cfg.setSecretKey("minioadmin");
        cfg.setWatchDir("D:\\upload");
        cfg.setAutoStart(false);
        cfg.setAutoWatch(false);
        cfg.setScanInterval(60);
        cfg.setMaxRetries(3); // 默认重试3次
        cfg.setRetryDelay(2); // 默认间隔2秒
        return cfg;
    }

    public static void save(MinioProperties cfg) throws Exception {
        Files.createDirectories(Path.of(APP_DIR));
        MAPPER.writerWithDefaultPrettyPrinter().writeValue(new File(CONFIG_PATH), cfg);
    }

    public static String getConfigPath() { return CONFIG_PATH; }
}
